﻿using UnityEngine;

public class BaseRaycastCube : MonoBehaviour
{
    private void Update()
    {
        if (Input.GetMouseButtonUp(0))
        {
            GameObject go = new GameObject("cube");
            CubeMesh cubeMesh = go.AddComponent<CubeMesh>();
            if (GetMouseRayPoint(out Vector3 cubePosition))
            {
                cubeMesh.TriaggulateCube(cubePosition);
                cubeMesh.Apply();
            }
            
        }
    }

    private bool GetMouseRayPoint(out Vector3 addCubePosition)
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            Debug.DrawRay(hitInfo.point, Vector3.up, Color.red);
            addCubePosition = CubeMetrics.FromWorldPositionToCubePosition(hitInfo.point);
            return true;
        }

        addCubePosition = Vector3.zero;
        return false;
    }

    private void OnDrawGizmos()
    {
        if (GetMouseRayPoint(out Vector3 cubePosition))
        {
            Gizmos.DrawWireCube(cubePosition, Vector3.one);
        }
    }
}
